<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="doAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="data">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page"
                :page-sizes="[1, 5, 10, 15]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="titleFn"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      :is-edit="isEdit"
      @close="hClose"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog=false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配权限弹层 -->
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showVisible"
    >
      <assignPermission @close="showVisible=false" />
    </el-dialog>
  </div>
</template>
<script>
import { getAllRoles, addRole, getDetailsById, updateById, deleteById } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  components: { assignPermission },
  data() {
    return {
      showVisible: false,
      isEdit: false,
      page: 1,
      pagesize: 10,
      data: [],
      total: 100,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules:
        {
          name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]

        }

    }
  },
  computed: {
    // 计算属性动态设置标题
    titleFn() {
      return this.isEdit ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    // 当点击了分配权限
    hAssign(row) {
      this.showVisible = true
    },
    // 获取所有角色列表
    async getRoles() {
      const res = await getAllRoles(this.page, this.pagesize)
      console.log(res)
      this.data = res.data.rows
      this.total = res.data.total
    },
    // 分页每页条数发生改变触发事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 重新获取数据
      this.getRoles()
    },
    // 页码发生改变触发事件
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      // 重新获取数据
      this.getRoles()
    },
    // 编辑功能
    async hEdit(row) {
      this.isEdit = true
      this.showDialog = true
      const res = await getDetailsById(row.id)
      console.log(res)
      this.roleForm = { ...row }
    },
    async doEdit() {
      try {
        await updateById(this.roleForm)
        this.getRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (error) {
        this.$message.error(error)
      }
    },
    doAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 新增 发请求
    async add() {
      try {
        await addRole(this.roleForm)
        this.getRoles()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (error) {
        this.$message.error(error)
      }
    },

    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.add()
        }
      })
    },
    hClose() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 当用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 发请求 根据id删除
        await deleteById(id)
        // bug修复的核心代码
        if (this.data.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 然后才发请求重新获取数据
        this.getRoles()
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>
